$(function(){
    const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value
    const message = $('#message')
    const message_container = $('#message_container')
    const spinner = $('#spinner')

    let max_count = 0
    let count = 0
    const startSpin = ()=>{
        spinner.removeClass('d-none')
    }
    
    
    const stopSpin = ()=>{
        spinner.addClass('d-none')
    }
    


    const printM = (m,color="",linefeed=true)=>{
        let toappend = m
        message_container.removeClass('d-none')
        if (linefeed){
            toappend = `<div class="text-${color}">${toappend}</div>`
        }else{
            toappend =`<span class="text-${color}">${toappend}</span>`
        }
        message.append(toappend)
        message_container.scrollTop(message_container.height());
    }
  
    const convertRequest = function(eform_id,cb,err_cb){
        const overwrite = $('#overwrite').prop('checked')
        $.ajax({
            type: 'post',
            url: convert_url,
            data: {
                eform_id,
                overwrite
            },
            headers:{
                'X-CSRFToken':csrf
            },
            dataType: "json",
            success: function (response) {
                if(cb){
                    cb(response)
                }
                count++
                if (count >= max_count){
                    stopSpin()
                }
            },
            error: function(request, status, error){
                if(err_cb){
                    err_cb(request, status, error)
                }
                count++
                if (count >= max_count){
                    stopSpin()
                }
            }
        });
    }

    const getSelectedID = function(){
        return $('.eform_checkbox:checkbox:checked')
    }

    $('#select_all').on('click',function(){
        const val = $(this).prop('checked')
        console.log(val)
        $('.eform_checkbox').prop('checked',val)
        console.log(getSelectedID())
    })

    

    $('#convert').on('click',function(){
        const selected = getSelectedID()
        max_count = selected.length
        count=0
        if (selected.length>0){

            startSpin()
            selected.each((i,v)=>{
                const id = $(v).data('id')
                convertRequest(id,function(res){
                    console.log(res.message)
                    console.log("Done")
                    const key = `#tr-${id}`
                    $(key).remove()
                    printM(res.message)
                },(req,s)=>{
                    printM(`EForm_id ${id} Convert Error: `+req.responseJSON.message.replace(/(\r\n|\n|\r)/gm, ""),'danger')
                })
            })
        }else{
            printM(`Please selected EForm to convert.`)
        }
    
    })


})